# -*- coding:UTF-8 -*-

from __future__ import print_function
import audio.audio_operator as ff
from speech.ibm.speech_recognition import IBMSpeechRecognizer
from translate.youdao.translate_recognition import YouDaoTranslateRecognizer
from queue import Queue
import threading, time
import integrate as inte


class Recognizer(threading.Thread):
    def __init__(self, inQueue, outQueue):
        super(Recognizer, self).__init__()
        self.inQueue = inQueue
        self.outQueue = outQueue
        self.__sr = IBMSpeechRecognizer()
        self.__status = threading.Event()
        self.__status.set()

    def run(self):
        while self.__status.isSet():
            data = self.inQueue.get()
            # 语音识别
            en_text = self.__sr.wav_file_recognition(data)
            if en_text is not None:
                en_text = en_text.replace('\n', ',')
                self.outQueue.put(en_text)
                print(en_text)

    def stop(self):
        self.__status.clear()


class Translation(threading.Thread):
    def __init__(self, inQueue, outQueue):
        super(Translation, self).__init__()
        self.inQueue = inQueue
        self.outQueue = outQueue
        self.__tr = YouDaoTranslateRecognizer()
        self.__status = threading.Event()
        self.__status.set()

    def run(self):
        while self.__status.isSet():
            data = self.inQueue.get()
            # 语音翻译
            zh_text = self.__tr.translate(data)
            self.outQueue.put(data)
            self.outQueue.put(zh_text)
            print(zh_text)

    def stop(self):
        self.__status.clear()


def checkThreads(queues, threads):
    while True:
        flag = True
        for i in range(len(queues)):
            if not queues[i].empty():
                flag = False
                break

        if flag:
            for i in range(len(threads)):
                threads[i].stop()
            break

        time.sleep(3)


def change(file):
    # 视频转换
    file_wav = inte.video_conversion(file)

    # 语音分割
    seg_point = inte.speech_segmentation(file_wav)
    print(seg_point)

    pathname, filename, typename = ff.get_info_path(file_wav)

    # 队列
    q1 = Queue(len(seg_point))
    q2 = Queue(len(seg_point))
    q3 = Queue(2*len(seg_point))

    for i in range(len(seg_point)):
        mini_name = pathname + filename + '/音频' + str(i + 1) + '.wav'
        q1.put(mini_name)

    # 线程
    t1 = Recognizer(q1, q2)
    t2 = Translation(q2, q3)
    tt = threading.Thread(target=checkThreads, args=([q1, q2], [t1, t2]))
    t1.start()
    t2.start()
    tt.start()
    tt.join()

    print('\n\n\n')
    print(q3.qsize())


if __name__ == '__main__':
    file = "E:/迅雷下载/videoplayback.mp4"
    change(file)
